﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Expression.Samples.Interactivity
{
	/// <summary>
	/// Executes a routed command
	/// </summary>
    public class ExecuteCommandAction : System.Windows.Interactivity.TargetedTriggerAction<UIElement>
    {
		/// <summary>
		/// Name of the command to be run
		/// </summary>
        public string Command
        {
            get { return (string)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        /// <summary>
        /// Backing DP for Command property
        /// </summary>
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(string), typeof(ExecuteCommandAction), new UIPropertyMetadata(null));

		/// <summary>
		/// Optional parameter for command.
		/// </summary>
        public object CommandParameter
        {
            get { return (object)GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

        /// <summary>
        /// Backing DP for CommandParameter property
        /// </summary>
        public static readonly DependencyProperty CommandParameterProperty =
			DependencyProperty.Register("CommandParameter", typeof(object), typeof(ExecuteCommandAction), new UIPropertyMetadata(null));


		/// <summary>
		/// Executes the command.
		/// </summary>
		/// <param name="parameter"></param>
        protected override void Invoke(object parameter)
        {
            CommandConverter typeConverter = new CommandConverter();
            RoutedUICommand commandToExecute;

            try
            {
                commandToExecute = typeConverter.ConvertFromString(this.Command) as RoutedUICommand;
            }
            catch (Exception e)
            {
                throw new ArgumentException(String.Format("Unable to convert \"{0}\" to a routed event. Verify that the specified string is a properly registered routed event and try again.", this.Command), e); 
            }

            commandToExecute.Execute(this.CommandParameter, this.Target);
        }
    }
}